package edu.cdnu.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import edu.cdnu.common.dto.CatalogueDto;
import edu.cdnu.dao.CatalogueDao;
import edu.cdnu.dao.FileDao;
import edu.cdnu.pojo.CataloguePojo;
import edu.cdnu.service.CatalogueService;

@Service
public class CatalogueServiceImpl implements CatalogueService {

	@Autowired
	private CatalogueDao catalogueDao;
	
	@Autowired
	private FileDao fileDao;
	
	@Override
	public List<CatalogueDto> selectCatalogueDtoListByCourseIdAndState(int courseId, Integer state) {
		if(state==null) {
			// 为空给默认值
			state=1;
		}
		
		// 根目录
		List<CatalogueDto> list= catalogueDao.selectCatalogueListByCourseIdAndParentIdAndState(courseId, 0, state);
		for(CatalogueDto c:list) {
			selectChildren(c);
		}
		return list;
	}
	/**
	 * 递归查询子目录
	 * @param catalogueDto
	 */
	private void selectChildren(CatalogueDto catalogueDto){
		// 通过id查子目录
		List<CatalogueDto> list=fileDao.selectCatalogueDtoByParentId(catalogueDto.getId());
		// 有，设置进去 并且查询下一级
		if(list.size()>0) {
			catalogueDto.setChildren(list);
			for(CatalogueDto c:list) {
				selectChildren(c);
			}
		}
		// 没有就不做操作
	}


	@Override
	public void addOrUpdateCatalogue(CataloguePojo cataloguePojo) {
		if(cataloguePojo == null) {
			return ;
		}else if(cataloguePojo.getId() == null) {
			// id为空 新增
			catalogueDao.insertCatalogue(cataloguePojo);
		}else {
			// 修改
			catalogueDao.updateCatalogueByCatalogueId(cataloguePojo);
		}
	}
	
	@Override
	public List<Integer> selectCatalogueListByCourseIdAndState(int courseId, Integer state) {
		if(state==null) {
			state=1;
		}
		return catalogueDao.selectCatalogueListByCourseIdAndState(courseId, state);
	}
	
	@Override
	public List<CatalogueDto> selectCatalogueDtoListByCourseIdAndState(int courseId, Integer parent, Integer state) {
		return catalogueDao.selectCatalogueListByCourseIdAndParentIdAndState(courseId, parent, state);
	}
	@Override
	public List<CataloguePojo> selectLeafCatalogueListByCourseIdAndState(int courseId, Integer state) {
		if(state==null) {
			state=2;
		}
		return catalogueDao.selectLeafCatalogueListByCourseIdAndState(courseId, state);
	}
}
